<template>
  <div class="financial-report-container">
    <div class="action-bar">
      <van-button type="primary" @click="showReportForm(null)">
        新增报表
      </van-button>
      <van-search
        v-model="searchQuery"
        placeholder="搜索报表类型"
        @search="onSearch"
      />
    </div>
    
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-swipe-cell v-for="report in reportList" :key="report.reportId">
        <van-card
          :title="report.reportType"
          :desc="`报表日期: ${formatDate(report.reportDate)}`"
        >
          <template #tags>
            <van-tag plain type="primary" style="margin-right: 5px;">
              ID: {{ report.reportId }}
            </van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click="showReportForm(report)">
              编辑
            </van-button>
            <van-button 
              size="mini" 
              type="danger" 
              @click="confirmDeleteReport(report.reportId)"
            >
              删除
            </van-button>
            <van-button 
              size="mini" 
              type="info" 
              @click="viewReportContent(report)"
            >
              查看内容
            </van-button>
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            type="danger"
            text="删除"
            @click="confirmDeleteReport(report.reportId)"
          />
        </template>
      </van-swipe-cell>
    </van-list>

    <!-- 报表表单对话框 -->
    <van-dialog
      v-model:show="showDialog"
      :title="currentReport ? '编辑报表' : '新增报表'"
      show-cancel-button
      @confirm="submitReportForm"
    >
      <van-form ref="reportFormRef">
        <van-cell-group inset>
          <van-field
            v-model="reportForm.reportType"
            label="报表类型"
            placeholder="请选择报表类型"
            readonly
            @click="showTypePicker = true"
            :rules="[{ required: true, message: '请选择报表类型' }]"
          />
          <van-field
            v-model="reportForm.reportDate"
            label="报表日期"
            placeholder="请选择日期"
            readonly
            @click="showDatePicker = true"
            :rules="[{ required: true, message: '请选择报表日期' }]"
          />
          <van-field
            v-model="reportForm.content"
            label="报表内容"
            placeholder="请输入报表内容"
            type="textarea"
            rows="4"
            autosize
            :rules="[{ required: true, message: '请输入报表内容' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <!-- 报表内容查看弹窗 -->
    <van-popup
      v-model:show="showContentPopup"
      position="bottom"
      round
      closeable
      :style="{ height: '60%', padding: '20px' }"
    >
      <h3>{{ currentReport?.reportType }} - {{ formatDate(currentReport?.reportDate) }}</h3>
      <div class="report-content">
        <pre>{{ currentReport?.content }}</pre>
      </div>
    </van-popup>

    <!-- 报表类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom">
<van-picker
  :columns="reportTypeOptions"
  @confirm="onConfirmType"
  @cancel="showTypePicker = false"
/>
</van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onConfirmDate"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Toast } from 'vant'
import { showConfirmDialog as Dialog } from 'vant'
import {  showFailToast } from 'vant'

// 使用方式
showFailToast('加载报表类型失败')
import { 
  getFinancialReports, 
  createFinancialReport, 
  updateFinancialReport, 
  deleteFinancialReport,
  getReportTypes
} from '@/api/financial'

// 数据列表相关
const reportList = ref([])
const loading = ref(false)
const finished = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = 10

// 表单相关
const showDialog = ref(false)
const reportFormRef = ref(null)
const currentReport = ref(null)
const reportForm = reactive({
  reportId: null,
  reportType: '',
  reportDate: '',
  content: ''
})

// 弹窗相关
const showContentPopup = ref(false)
const showTypePicker = ref(false)
const showDatePicker = ref(false)
const reportTypeOptions = ref([])
const currentDate = ref([])

// 初始化加载报表类型
onMounted(async () => {
  try {
    const response = await getReportTypes();
    console.log('API原始响应:', response); // 调试日志
    
    // 处理不同格式的响应
    let types = [];
    if (Array.isArray(response)) {
      types = response;
    } else if (response?.data) {
      types = Array.isArray(response.data) ? response.data : [response.data];
    } else if (response?.list) {
      types = Array.isArray(response.list) ? response.list : [response.list];
    }
    
    console.log('处理后的类型列表:', types); // 调试日志
    reportTypeOptions.value = types.map(type => ({
      text: typeof type === 'string' ? type : type.name || type.value || type.id,
      value: typeof type === 'string' ? type : type.value || type.id || type.name
    }));
  } catch (error) {
    console.error('加载报表类型失败:', error);
    showFailToast('加载报表类型失败');
  }
});

// 加载报表数据
const onLoad = async () => {
try {
  loading.value = true;
  const params = {
    page: currentPage.value,
    pageSize,
    search: searchQuery.value
  };
  
  const res = await getFinancialReports(params);
  console.log('API响应:', res); // 调试日志
  
  // 根据实际返回结构调整
  const dataList = res.data?.list || res.data?.records || [];
  const totalItems = res.data?.total || 0;
  
  if (dataList.length > 0) {
    reportList.value = [...reportList.value, ...dataList];
    currentPage.value++;
    
    if (dataList.length < pageSize) {
      finished.value = true;
    }
  } else {
    finished.value = true;
  }
} catch (error) {
  console.error('加载数据错误:', error);
  Toast.fail('加载报表列表失败');
} finally {
  loading.value = false;
}
}

// 搜索报表
const onSearch = () => {
  reportList.value = []
  currentPage.value = 1
  finished.value = false
  onLoad()
}

// 显示报表表单
const showReportForm = (report) => {
  if (report) {
    currentReport.value = report
    Object.assign(reportForm, {
      reportId: report.reportId,
      reportType: report.reportType,
      reportDate: report.reportDate,
      content: report.content
    })
    
    // 设置日期选择器默认值
    if (report.reportDate) {
      const date = new Date(report.reportDate)
      currentDate.value = [
        date.getFullYear(),
        date.getMonth() + 1,
        date.getDate()
      ]
    }
  } else {
    currentReport.value = null
    resetReportForm()
    
    // 设置日期选择器为今天
    const today = new Date()
    currentDate.value = [
      today.getFullYear(),
      today.getMonth() + 1,
      today.getDate()
    ]
  }
  showDialog.value = true
}

// 重置表单
const resetReportForm = () => {
  reportForm.reportId = null
  reportForm.reportType = ''
  reportForm.reportDate = ''
  reportForm.content = ''
}

// 提交表单
const submitReportForm = async () => {
  try {
    await reportFormRef.value.validate()
    
    if (currentReport.value) {
      await updateFinancialReport(currentReport.value.reportId, reportForm)
      showFailToast('报表更新成功')
    } else {
      await createFinancialReport(reportForm)
      showFailToast('报表创建成功')
    }
    
    showDialog.value = false
    refreshList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 确认删除报表
const confirmDeleteReport = (id) => {
  Dialog({
    title: '删除确认',
    message: '确定要删除这份报表吗？此操作不可撤销。',
  }).then(() => {
    deleteFinancialReport(id).then(() => {
      showFailToast('报表删除成功')
      reportList.value = reportList.value.filter(item => item.reportId !== id)
    }).catch(() => {
      showFailToast('删除报表失败')
    })
  }).catch(() => {
    // 取消删除
  })
}
// 查看报表内容
const viewReportContent = (report) => {
  currentReport.value = report
  showContentPopup.value = true
}

// 刷新列表
const refreshList = () => {
  reportList.value = []
  currentPage.value = 1
  finished.value = false
  onLoad()
}// 日期选择确认
const onConfirmDate = ({ selectedValues }) => {
  const [year, month, day] = selectedValues
  reportForm.reportDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  showDatePicker.value = false
}

// 类型选择确认
const onConfirmType = ({ selectedValues }) => {
  console.log('选择的类型:', selectedValues); // 调试日志

  reportForm.reportType = selectedValues[0]
  showTypePicker.value = false
}

// 格式化日期显示
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  } catch {
    return dateStr
  }
}
</script>

<style scoped>
.financial-report-container {
  padding: 12px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.van-card {
  margin-bottom: 10px;
}

.report-content {
  margin-top: 15px;
  padding: 10px;
  background-color: #f7f8fa;
  border-radius: 4px;
  max-height: calc(100% - 50px);
  overflow: auto;
}

.report-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
}
</style>